<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0"
    />
    <title>Document</title>
  </head>
  <body>
    <script>
      const ALLOWED_ORIGIN = 'https://main-site.com'; // 只接收主界面的请求
      const encode = (data) => btoa(JSON.stringify(data));
      const decode = (str) => JSON.parse(atob(str));
      /* // 消息监听 */
      window.addEventListener('message', (event) => {
        if (event.origin !== ALLOWED_ORIGIN) return;

        try {
          const msg = decode(event.data);
          const data = decode(msg.data);

          // 处理命令
          if (data.command === 'print') {
            console.log(
              `${window.name} 收到来自${msg.from}的消息: ${data.text}`
            );

            // 返回响应
            const response = {
              type: 'response',
              key: msg.key,
              from: window.name,
              to: msg.from,
              data: encode({ status: 'success' }),
            };
            parent.postMessage(encode(response), '*');
          }
        } catch (e) {
          console.error('消息处理错误:', e);
        }
      });
      // 测试场景：iframe2发送消息到iframe3的示例
      function sendToIframe3() {
        const msg = {
          type: 'request',
          key: 'msg_' + Date.now(),
          from: 'iframe2',
          to: 'iframe3',
          data: encode({ command: 'print', text: 'Hello from iframe2' }),
          via: 'parent',
        };
        parent.postMessage(encode(msg), '*');
      }
    </script>
  </body>
</html>
